
Ext.namespace('mapfish.widgets');

mapfish.widgets.Printing = function(config){
    Ext.apply(this, config);
    mapfish.widgets.Printing.superclass.constructor.call(this);
}

Ext.extend(mapfish.widgets.Printing, Ext.Container, {

    /**
     * Property: frameWidth
     * {String}
     */
    frameWidth: null,
    
    /**
     * Property: frameHeight
     * {String}
     */
    frameHeight: null,
    
    /**
     * Property: frameScale
     * {String}
     */
    frameScale: null,
    
    /**
     * Property: marginX
     * {Double}
     */
    marginX: 0.013,
    
    /**
     * Property: marginY
     * {Double}
     */
    marginY: 0.013,
    
    /**
     * Property: marginTitle
     * {Double}
     */
    marginTitle: 0.03,
    
    
    
    mainTemplate: new Ext.Template(
                                   '<div style="margin:10px 5px 5px 5px">', 
                                   '<table border="0">',
                                   '<tr><td><input type="text" id="format" size="15"/></td></tr>',
                                   '<tr><td>&nbsp;</td></tr>',
                                   '<tr><td><input type="text" id="orientation" size="15"/></td></tr>',
                                   '<tr><td>&nbsp;</td></tr>',                                   
                                   '<tr><td><input type="text" id="scale" size="15"/></td></tr>',
                                   '<tr><td>&nbsp;</td></tr>',
                                   '<tr><td><div id="dragForm" ></div></td></tr>',
                                   '<tr><td>&nbsp;</td></tr>',
                                   '<tr><td><div id="button" ></div></td></tr>',
                                   '</table>', 
                                   '</div>'),
    
    
    initComponent: function(){
    
    
    
    },
    
    
    // private
    onRender: function(container, position){
        if (!this.el) {
            this.el = document.createElement('div');
        }
        
        mapfish.widgets.Printing.superclass.onRender.apply(this, arguments);
        
        this.mainTemplate.overwrite(this.el, {});
        
        var store1 = new Ext.data.SimpleStore({
            fields: ['value', 'text'],
            data: [['A4', 'A4'], ['A3', 'A3'], ['A2', 'A2'], ['A1', 'A1'], ['A0', 'A0']]
        });
        
        var combo1 = new Ext.form.ComboBox({
            name: 'format',
            hiddenName: 'paperformat',
            store: store1,
            valueField: 'value',
            displayField: 'text',
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Format...',
            selectOnFocus: true,
            applyTo: 'format'
        });
        
        
        var store2 = new Ext.data.SimpleStore({
            fields: ['value', 'text'],
            data: [['landscape', 'Landscape'], ['portrait', 'Portrait']]
        });
        
        var combo2 = new Ext.form.ComboBox({
            name: 'orientation',
            hiddenName: 'paperorientation',
            store: store2,
            valueField: 'value',
            displayField: 'text',
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Orientation...',
            selectOnFocus: true,
            applyTo: 'orientation'
        });
        
        
        var store3 = new Ext.data.SimpleStore({
            fields: ['value', 'text'],
            data: [[10, '1:10'], [20, '1:20'], [50, '1:50'], [100, '1:100'], [250, '1:250']]
        });
        
        var combo3 = new Ext.form.ComboBox({
            name: 'scale',
            hiddenName: 'mapscale',
            store: store3,
            valueField: 'value',
            displayField: 'text',
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Scale...',
            selectOnFocus: true,
            applyTo: 'scale'
        });

          
        combo1.on('select', function() {
        	this.showPdfFrame();
        },this);
        combo2.on('select', function() {
        	this.showPdfFrame();
        },this);
        combo3.on('select', function() {
        	this.showPdfFrame();
        },this);        
        
        
        var ok_button = new Ext.Button({
            text: 'Print',
            applyTo: 'button'
        });
        
        ok_button.on('click', function(){
             this.printPdf();
        }, this);
        
        
        
        var dragForm = new Ext.FormPanel({
            labelWidth: 80, // label settings here cascade unless overridden
            //url:'save-form.php',
            //frame:true,
            //title: 'Simple Form',
            bodyStyle: 'padding:5px 5px 0',
            width: 120,
            id: 'form1',
            //defaultType: 'textfield',
            
            items: [new Ext.form.Checkbox({
                fieldLabel: 'Move frame',
                disabled: true,
                name: 'dragChBox',
                id: 'dragBoxId'
            })]
        });
        dragForm.render('dragForm');
        

    
    },
    
    

    printPdf: function() {
     
        // check if format, orientation and scale is chosen        
        var paperformat = Ext.get('paperformat').getValue();
        if (!paperformat) {
            Ext.MessageBox.alert('Error', 'You must choose a format.');
            return;
        }
        var paperorientation = Ext.get('paperorientation').getValue();
        if (!paperorientation) {
            Ext.MessageBox.alert('Error', 'You must choose an orientation.');
            return;
        }
        var mapscale = Ext.get('mapscale').getValue();
        this.frameScale = mapscale;
        if (!mapscale) {
            Ext.MessageBox.alert('Error', 'You must choose a scale.');
            return;
        }        

        var frameLayer = this.map.getLayersByName("PDF-Frame");
        var bbox = frameLayer[0].features[0].geometry.getBounds().toBBOX();

        var millisec = new Date().getTime();
        
        var selFeatureLayers = '%3B';

        for (i=0;i<this.map.layers.length;i++){
            var layer=this.map.layers[i];
            if(!(layer.isVector || layer.isBaseLayer)) {
                selFeatureLayers = selFeatureLayers + 'caa%3Awalls%3Bwms%3B1%3Bapplication%2Fpdf%3B' + layer.params.FEATUREID + '%3B';
            } 
        }        
       
        selFeatureLayers = selFeatureLayers.substring(0,selFeatureLayers.length-3);

        
        var pdfUrl = 'http://localhost:8080/MapComposerOne/GetMap?mode=3&size=' + paperformat + '&orientation=' + paperorientation + '&scale=' + mapscale + '&title=CAA%202008&timestamp=' + millisec + '&datalayers=caa%3Aisolines%3Bwms%3B1%3Bapplication%2Fpdf%3B%3Bcaa%3Aareas%3Bwms%3B1%3Bapplication%2Fpdf%3B' + selFeatureLayers + '&BBOX=' + bbox;
        
        //alert(pdfUrl);
        
        
        window.open(pdfUrl,"CAA 2008");
        
    },
    
    
    showPdfFrame: function(){
    
        // check if format, orientation and scale is chosen        
        var paperformat = Ext.get('paperformat').getValue();
        if (!paperformat) {
            //Ext.MessageBox.alert('Error', 'You must choose a format.');
            return;
        }
        var paperorientation = Ext.get('paperorientation').getValue();
        if (!paperorientation) {
            //Ext.MessageBox.alert('Error', 'You must choose an orientation.');
            return;
        }
        var mapscale = Ext.get('mapscale').getValue();
        this.frameScale = mapscale;
        if (!mapscale) {
            //Ext.MessageBox.alert('Error', 'You must choose a scale.');
            return;
       }
        
        // enable the drag checkbox
        Ext.getCmp('dragBoxId').enable();
        
        // a style for the pdf frame
        var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
        layer_style.fillOpacity = 0.2;
        layer_style.fillColor = "#66ff00";
        layer_style.strokeColor = "#66ff00";
        layer_style.strokeWidth = 2;
        layer_style.graphicOpacity = 1;
        
        // calculate the papersize in meters w/o the margins
        this.setFrameSize(paperformat, paperorientation);
        
        // resolution of the map [meters per pixel]
        mapRes = this.map.getResolution();
        
        
        if (this.map.getLayersByName("PDF-Frame").length == 0) {
            var xl = this.map.getCenter().lon;
            var yl = this.map.getCenter().lat;
            
            var frameGeom = new OpenLayers.Bounds(xl, yl, xl + this.frameWidth * this.frameScale, yl + this.frameHeight * this.frameScale).toGeometry();
            var frameFeat = new OpenLayers.Feature.Vector(frameGeom, null, null);
            
            var frameLayer = new OpenLayers.Layer.Vector("PDF-Frame", {
                style: layer_style
            });
            frameLayer.addFeatures([frameFeat]);
            this.map.addLayer(frameLayer);
            
            var dragControl = new OpenLayers.Control.DragFeature(frameLayer);
            this.map.addControl(dragControl);
            
            Ext.getCmp('dragBoxId').on('check', function(){
                if (Ext.getCmp('dragBoxId').getValue()) {
                    dragControl.activate();
                }
                else {
                    dragControl.deactivate();
                }
            });
            
        }
        else {
            var frameLayer = this.map.getLayersByName("PDF-Frame");
            var xl = frameLayer[0].features[0].geometry.getBounds().toArray()[0];
            var yl = frameLayer[0].features[0].geometry.getBounds().toArray()[1];
            
            var frameGeom = new OpenLayers.Bounds(xl, yl, xl + this.frameWidth * this.frameScale, yl + this.frameHeight * this.frameScale).toGeometry();
            var frameFeat = new OpenLayers.Feature.Vector(frameGeom, null, null);
            
            frameLayer[0].removeFeatures(frameLayer[0].features);
            frameLayer[0].addFeatures([frameFeat]);
        }
        
    },
    
    
    setFrameSize: function(paperformat, paperorientation){
    
        if (paperformat == "A4") {
            if (paperorientation == "landscape") {
                this.frameWidth = 0.297 - 2 * this.marginX - this.marginTitle;
                this.frameHeight = 0.210 - 2 * this.marginY;
            }
            if (paperorientation == "portrait") {
                this.frameWidth = 0.210 - 2 * this.marginX;
                this.frameHeight = 0.297 - 2 * this.marginY - this.marginTitle;
            }
        }
        
        if (paperformat == "A3") {
            if (paperorientation == "landscape") {
                this.frameWidth = 0.420 - 2 * this.marginX - this.marginTitle;
                this.frameHeight = 0.297 - 2 * this.marginY;
            }
            if (paperorientation == "portrait") {
                this.frameWidth = 0.297 - 2 * this.marginX;
                this.frameHeight = 0.420 - 2 * this.marginY - this.marginTitle;
            }
        }
        
        if (paperformat == "A2") {
            if (paperorientation == "landscape") {
                this.frameWidth = 0.594 - 2 * this.marginX - this.marginTitle;
                this.frameHeight = 0.420 - 2 * this.marginY;
            }
            if (paperorientation == "portrait") {
                this.frameWidth = 0.420 - 2 * this.marginX;
                this.frameHeight = 0.594 - 2 * this.marginY - this.marginTitle;
            }
        }
        
        if (paperformat == "A1") {
            if (paperorientation == "landscape") {
                this.frameWidth = 0.841 - 2 * this.marginX - this.marginTitle;
                this.frameHeight = 0.594 - 2 * this.marginY;
            }
            if (paperorientation == "portrait") {
                this.frameWidth = 0.594 - 2 * this.marginX;
                this.frameHeight = 0.841 - 2 * this.marginY - this.marginTitle;
            }
        }
        
        if (paperformat == "A0") {
            if (paperorientation == "landscape") {
                this.frameWidth = 1.189 - 2 * this.marginX - this.marginTitle;
                this.frameHeight = 0.841 - 2 * this.marginY;
            }
            if (paperorientation == "portrait") {
                this.frameWidth = 0.841 - 2 * this.marginX;
                this.frameHeight = 1.189 - 2 * this.marginY - this.marginTitle;
            }
        }
    }
});

Ext.reg('printing', mapfish.widgets.Printing);
